package com.csstu.tomcat.http;

import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * @program: cstomcat
 * @description: 封装http请求
 * @author: 程硕
 * @create: 2025-08-16 18:14
 **/
@Data
public class CsRequest {
    
    private InputStream inputStream;
    private String method;
    private String uri;
    // 存放参数列表 参数名->参数值 => HashMap
    private HashMap<String, String> paramsMapping =
            new HashMap<>();

    //构造方法
    //inputStream 是和socket关联的
    public CsRequest(InputStream inputStream) {
        this.inputStream = inputStream;
        encapHttpRequest();
    }
    // request对象有一个特别重要方法：getParameter
    public String getParameter(String name) {
        if (paramsMapping.containsKey( name)){
            return paramsMapping.get(name);
        }else {
            return "";
        }
    }
    // 初始化
    public void encapHttpRequest() {
        //inputStream 转换成 bufferRead
        try {
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            //读取第一行
            /***
             * Get /csCalServlet?num1=10&num2=20 HTTP/1.1
             * Host: localhost:8080
             * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0
             */
            String requestLine = bufferedReader.readLine();
            //得到method
            String[] requestLineArr = requestLine.split(" ");
            method = requestLineArr[0];
            //解析得到 /csCalServlet
            int index = requestLineArr[1].indexOf("?");
            if (index == -1) { //说明没有参数列表
                uri = requestLineArr[1];
            }else {
                uri = requestLineArr[1].substring(0, index);
                //获取参数列表->
                String parameters = requestLineArr[1].substring(index + 1);
                String[] parameterPair = parameters.split("&");
                //防止用户传入空参数
                if (null != parameterPair && !"".equals(parameterPair)){
                    //再次分割
                    for (String pair : parameterPair) {
                        String[] pairArr = pair.split("=");
                        if (pairArr.length == 2) {
                            paramsMapping.put(pairArr[0], pairArr[1]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
